<?php

namespace app\applet\controller;

use app\common\model\WxUsers;

class Index extends Base
{

    private $appid = '';
    private $appsecret = '';

    /**
     * @api {GET} /applet/login 小程序登陆
     * @apiGroup 通用信息
     * @apiParamExample {json} 参数
     * {
     *      "code":"1311234567",      // code
     * }
     * @apiSuccessExample {json} 返回
     * {
     *     "code": 1,
     *     "msg": "请求成功",
     *     "data": [
     *         {
     *             "id": "12346",    // 用户id
     *             "read_strategy":0 ,   // 是否已读攻略  0否  1是
     *             "token": "wangshaoqiu.png",
     *         }
     *     ],
     *     "url": "",
     *     "wait": 3
     * }
     */
    public function login()
    {
        $code = input('code');
        if (!$code) {
            return $this->error('参数错误！');
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->appsecret&js_code={$code}&grant_type=authorization_code";
        $userResult = json_decode(file_get_contents($url), true);
        // 判断是否登陆成功
        $openid = isset($userResult['openid']) ? $userResult['openid'] : "";
        if (empty($openid)) {
            return $this->error('参数错误，登陆失败');
        }
        // 获取用户信息
        $userInfo = WxUsers::where(['openid' => $openid])->find();
        // 生成token
        $clientiparr = explode('.', get_client_ip());
        $clientnum = array_sum($clientiparr);
        $token = uuid() . '-' . $clientnum;
        $data['token'] = $token;
        // 判断用户是否存在
        if (!$userInfo) {
            // 用户openid写入数据库
            $data['openid'] = $openid;
            $data['created_at'] = date('Y-m-d H:i:s');
            $id = WxUsers::insertGetId($data);
        }else{
            $id = $userInfo['id'];
        }
        // 用户信息放入缓存
        $cacheInfo = ['id' => $id, 'openid' => $openid];
        $login_cache = cache('applet_login');
        $login_cache[$token] = $cacheInfo;
        cache('applet_login', $login_cache, 2 * 60 * 60);
        return $this->success('登陆成功', '',['id'=>$id,'read_strategy'=>$userInfo['read_strategy'],'token'=>$token]);
    }

}